package com.wwd.algorithm.data_structure;

/**
 * 数组
 */
public class Array<E> {
    private int size;
    private E[] elements;


    public Array() throws IllegalAccessException {
        this(10);
    }

    public Array(int capacity) throws IllegalAccessException {
        if (capacity <= 0 || capacity > Integer.MAX_VALUE) {
            throw new IllegalAccessException("数组初始化异常；errorMessage: 数组容量非法");
        }
        this.size = capacity;
        this.elements = (E[]) new Object[size];
    }

    public int getSize(){
        return size;
    }

    public boolean isEmpty(){
        return size == 0;
    }

    public void addLast(E e){
        add(0,e);
    }

    public void addFirst(E e){
        add(size,e);
    }

    public void add(int index, E e) {
        // 边界条件校验
        // 扩容
        expansion(size + 1);
        for (int i = size; i > index; i--) {
            elements[i + 1] = elements[i];
        }
        size++;
    }

    public void remove(int index) {
        // 边界条件校验
        for (int i = index; i < size - 1; i++) {
            elements[i] = elements[i + 1];
        }
        size --;
    }

    public void removeLast() {
        remove(0);
    }

    public void removeFirst() {
        remove(size - 1);
    }

    public void expansion(int capacity) {
        // 边界条件校验
        int oldCapacity = elements.length;
        if (oldCapacity <= capacity) {
            // 扩容
            int newCapacity = oldCapacity + (oldCapacity >> 1);
            E[] newElement = (E[])new Object[]{newCapacity};
            for (int i = 0; i < elements.length; i++) {
                newElement[i] = elements[i];
            }
            elements = newElement;
            size = newCapacity;
        }
    }

    public int indexOf(E element){
        for (int i = 0; i < elements.length; i++) {
            if(elements[i].equals(element)) return i;
        }
        return -1;
    }
}
